import 'package:dio/dio.dart';
import 'package:flutter_250303/http/print_log_interceptor.dart';
import 'package:flutter_250303/http/response_interceptor.dart';

class DioInstance {
  static DioInstance? _instance;

  final Dio _dio = Dio();

  DioInstance._();

  static DioInstance instance() {
    return _instance ??= DioInstance._();
  }

  final _defaultTime = Duration(seconds: 30);

  void initDio({String? httpMethod = HttpMethod.GET,
    String? baseurl,
    Duration? connectTimeout,
    Duration? receiveTimeout,
    Duration? sendTimeout,
    ResponseType? responseType = ResponseType.plain,
    String? contentType}) {
    BaseOptions options = BaseOptions(
        method: httpMethod,
        baseUrl: baseurl ?? "https://www.wanandroid.com/",
        connectTimeout: connectTimeout ?? _defaultTime,
        receiveTimeout: receiveTimeout ?? _defaultTime,
        sendTimeout: sendTimeout ?? _defaultTime,
        responseType: responseType,
        contentType: contentType);
    _dio.options = options;
    _dio.interceptors.add(PrintLogInterceptor());
    _dio.interceptors.add(ResponseInterceptor());
  }

  Future<Response> get({required String path,
    Map<String, dynamic>? param,
    Options? options,
    CancelToken? cancelToken}) async {
    return _dio.get(path,
        queryParameters: param,
        options: options ??
            Options(
                method: HttpMethod.GET,
                receiveTimeout: _defaultTime,
                sendTimeout: _defaultTime),
        cancelToken: cancelToken);
  }

  Future<Response> post({required String path,
    Object? data,
    Map<String, dynamic>? queryParm,
    Options? options,
    CancelToken? cancelToken}) async {
    return _dio.post(path, queryParameters: queryParm,
        data: data,
        cancelToken: cancelToken,
        options: options ?? Options(
            method: HttpMethod.POST,
            receiveTimeout: _defaultTime,
            sendTimeout: _defaultTime));
  }
}

class HttpMethod {
  static const String GET = "GET";
  static const String POST = "POST";
  static const String PUT = "PUT";
  static const String DELETE = "DELETE";
  static const String OPTIONS = "OPTIONS";
  static const String CONNECT = "CONNECT";
  static const String TRACE = "TRACE";
}
